package com.csun.dsms.service.impl;

import com.csun.dsms.comment.base.enums.ErrorCodeEnum;
import com.csun.dsms.comment.base.exception.BusinessException;
import com.csun.dsms.comment.core.support.BaseService;
import com.csun.dsms.mapper.DsmsStaffMapper;
import com.csun.dsms.model.domain.*;
import com.csun.dsms.model.dto.staff.StaffDto;
import com.csun.dsms.model.dto.staff.StaffQueryDto;
import com.csun.dsms.model.enums.RoleCodeEnum;
import com.csun.dsms.model.enums.StaffStatusEnum;
import com.csun.dsms.model.enums.UserSourceEnum;
import com.csun.dsms.model.enums.UserTypeEnum;
import com.csun.dsms.model.vo.staff.ApplyStaffDto;
import com.csun.dsms.model.vo.staff.StaffNumberVo;
import com.csun.dsms.model.vo.staff.StaffVo;
import com.csun.dsms.service.*;
import com.csun.dsms.utils.IDCardUtil;
import com.csun.dsms.utils.MD5;
import com.csun.dsms.utils.PublicUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-22 16:56
 * @description: TODO
 */
@Service
@Transactional
public class DsmsStaffServiceImpl extends BaseService<DsmsStaff> implements DsmsStaffService {

    @Resource
    private DsmsStaffMapper dsmsStaffMapper;
    @Resource
    private DsmsUserService dsmsUserService;
    @Resource
    private DsmsUnitService dsmsUnitService;
    @Resource
    private DsmsAreaService dsmsAreaService;
    @Resource
    private DsmsRoleUserService dsmsRoleUserService;
    @Resource
    private DsmsUnitUserService dsmsUnitUserService;
    @Resource
    private DsmsRoleService dsmsRoleService;

    /**
     * 查询服务人员列表.
     *
     * @param staffQueryDto the user query dto
     * @return the staff vo list.
     */
    @Override
    public List<StaffVo> queryListWithPage(StaffQueryDto staffQueryDto) {

        PageHelper.startPage(staffQueryDto.getPageNum(), staffQueryDto.getPageSize());

        return dsmsStaffMapper.queryListWithPage(staffQueryDto);
    }

    /**
     * 新增服务人员
     *
     * @param staffDto the staff dto
     * @return the int.
     */
    @Override
    public Integer save(StaffDto staffDto, DsmsUser login) {

        if (!dsmsUserService.checkIdCard(null, staffDto.getIdCard())) {
            throw new BusinessException(ErrorCodeEnum.GB10051002, staffDto.getIdCard());
        }

        if (!dsmsUserService.checkMobileNo(null, staffDto.getMobileNo())) {
            // 存在重复的手机号
            throw new BusinessException(ErrorCodeEnum.GB10011031, staffDto.getMobileNo());
        }

        if (!IDCardUtil.isIDNumber(staffDto.getIdCard())){
            throw new BusinessException(ErrorCodeEnum.GB10051009, staffDto.getIdCard());
        }

        DsmsUnit dsmsUnit = dsmsUnitService.selectByKey(staffDto.getUnitId());
        if (PublicUtil.isEmpty(dsmsUnit)) {
            throw new BusinessException(ErrorCodeEnum.GB10051003, dsmsUnit.getName());
        }
        if (!dsmsUnit.getUnitType().equals(2)) {
            throw new BusinessException(ErrorCodeEnum.GB10051003, dsmsUnit.getName());
        }

        DsmsArea dsmsArea = dsmsAreaService.selectByKey(staffDto.getAreaId());
        if (PublicUtil.isEmpty(dsmsArea)) {
            throw new BusinessException(ErrorCodeEnum.GB10051004, dsmsArea.getName());
        }

        DsmsUser dsmsUser = new DsmsUser();
        BeanUtils.copyProperties(staffDto, dsmsUser);
        dsmsUser.setUserName(staffDto.getName());
        dsmsUser.setLoginName(staffDto.getMobileNo());
        dsmsUser.setLoginPwd(MD5.getMd5().getMD5ofStr(staffDto.getLoginPwd()));
        dsmsUser.setStatus(StaffStatusEnum.ENABLE.getType());
        dsmsUser.setUpdateInfo(login);

        DsmsUser userQuery = new DsmsUser();
        userQuery.setLoginName(dsmsUser.getLoginName());
        int count = dsmsUserService.selectCount(userQuery);
        if (count > 0) {
            throw new BusinessException(ErrorCodeEnum.GB10011032, dsmsUser.getLoginName());
        }

        dsmsUser.setType(UserTypeEnum.STAFF_EMP.getKey());
        dsmsUser.setUserSource(UserSourceEnum.INSERT.getKey());

        DsmsRole dsmsRole = dsmsRoleService.selectByRoleCode(RoleCodeEnum.STAFF.getCode());
        if (PublicUtil.isEmpty(dsmsRole)) {
            throw new BusinessException(ErrorCodeEnum.GB10021010);
        }

        Integer result = dsmsUserService.save(dsmsUser);
        if (result > 0) {
            DsmsRoleUser dsmsRoleUser = new DsmsRoleUser();
            dsmsRoleUser.setUserId(dsmsUser.getId());
            dsmsRoleUser.setRoleId(dsmsRole.getId());
            dsmsRoleUserService.save(dsmsRoleUser);

            DsmsUnitUser dsmsUnitUser = new DsmsUnitUser();
            dsmsUnitUser.setUserId(dsmsUser.getId());
            dsmsUnitUser.setUnitId(staffDto.getUnitId());
            dsmsUnitUserService.save(dsmsUnitUser);
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        BeanUtils.copyProperties(staffDto, dsmsStaff);
        dsmsStaff.setUpdateInfo(login);
        dsmsStaff.setUserId(dsmsUser.getId());

        return dsmsStaffMapper.insertSelective(dsmsStaff);
    }

    /**
     * 修改服务人员
     *
     * @param login    the login user
     * @param staffDto the staff dto
     * @return the int.
     */
    @Override
    public Integer edit(StaffDto staffDto, DsmsUser login) {

        DsmsStaff dsmsStaffQuery = dsmsStaffMapper.selectByPrimaryKey(staffDto.getId());
        if (PublicUtil.isEmpty(dsmsStaffQuery)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }

        DsmsUser dsmsUser = new DsmsUser();
        dsmsUser.setId(dsmsStaffQuery.getUserId());
        dsmsUser.setUpdateInfo(login);

        // 姓名
        if (PublicUtil.isNotEmpty(staffDto.getName())) {
            dsmsUser.setUserName(staffDto.getName());
        }

        // 身份证号
        if (PublicUtil.isNotEmpty(staffDto.getIdCard())) {
            if (!dsmsUserService.checkIdCard(dsmsStaffQuery.getUserId(), staffDto.getIdCard())) {
                throw new BusinessException(ErrorCodeEnum.GB10051002);
            }
            dsmsUser.setIdCard(staffDto.getIdCard());
        }

        // 手机号
        if (PublicUtil.isNotEmpty(staffDto.getMobileNo())) {
            if (!dsmsUserService.checkMobileNo(dsmsStaffQuery.getUserId(), staffDto.getMobileNo())) {
                throw new BusinessException(ErrorCodeEnum.GB10011031);
            }
            dsmsUser.setMobileNo(staffDto.getMobileNo());
            dsmsUser.setLoginName(staffDto.getMobileNo());
        }

        // 性别
        if (PublicUtil.isNotEmpty(staffDto.getSex())) {
            dsmsUser.setSex(staffDto.getSex());
        }

        // 生日
        if (PublicUtil.isNotEmpty(staffDto.getBirthday())) {
            dsmsUser.setBirthday(staffDto.getBirthday());
        }

        // 头像
        if (PublicUtil.isNotEmpty(staffDto.getHeadPic())) {
            dsmsUser.setHeadPic(staffDto.getHeadPic());
        }
        dsmsUserService.update(dsmsUser);

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setId(staffDto.getId());
        dsmsStaff.setUpdateInfo(login);

        // 所属公司
        if (PublicUtil.isNotEmpty(staffDto.getUnitId())) {
            DsmsUnitUser dsmsUnitUser = new DsmsUnitUser();
            dsmsUnitUser.setUserId(dsmsUser.getId());
            dsmsUnitUserService.delete(dsmsUnitUser);

            dsmsUnitUser.setUnitId(staffDto.getUnitId());
            dsmsUnitUserService.save(dsmsUnitUser);

            dsmsStaff.setUnitId(staffDto.getUnitId());
        }

        // 片区
        if (PublicUtil.isNotEmpty(staffDto.getAreaId())) {
            dsmsStaff.setAreaId(staffDto.getAreaId());
        }

        // 服务年限
        if (PublicUtil.isNotEmpty(staffDto.getServiceLength())) {
            dsmsStaff.setServiceLength(staffDto.getServiceLength());
        }

        // 服务技能
        if (PublicUtil.isNotEmpty(staffDto.getSkill())) {
            dsmsStaff.setSkill(staffDto.getSkill());
        }

        // 备注
        if (PublicUtil.isNotEmpty(staffDto.getRemark())) {
            dsmsStaff.setRemark(staffDto.getRemark());
        }

        return dsmsStaffMapper.updateByPrimaryKeySelective(dsmsStaff);
    }

    /**
     * 通过Id删除服务人员.
     *
     * @param staffId the staff id
     * @return the int.
     */
    @Override
    public Integer deleteById(Long staffId) {

        DsmsStaff dsmsStaffQuery = dsmsStaffMapper.selectByPrimaryKey(staffId);
        if (PublicUtil.isEmpty(dsmsStaffQuery)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }

        // 删除用户
        dsmsUserService.deleteUserById(dsmsStaffQuery.getUserId());

        return dsmsStaffMapper.deleteByPrimaryKey(staffId);
    }

    /**
     * 通过Id查询服务人员.
     *
     * @param staffId the staff id
     * @return the int
     */
    @Override
    public StaffVo showById(Long staffId) {

        return dsmsStaffMapper.showById(staffId);
    }

    /**
     * 审核服务人员.
     *
     * @param applyStaffDto the apply staff dto
     * @return the int.
     */
    @Override
    public Integer apply(ApplyStaffDto applyStaffDto, DsmsUser login) {

        DsmsStaff dsmsStaffQuery = dsmsStaffMapper.selectByPrimaryKey(applyStaffDto.getStaffId());
        if (PublicUtil.isEmpty(dsmsStaffQuery)) {
            throw new BusinessException(ErrorCodeEnum.GB10051001);
        }

        if (dsmsStaffQuery.getApply() > 0) {
            throw new BusinessException(ErrorCodeEnum.GB10051005);
        }

        if (applyStaffDto.getApply().equals(2)) {
            if (PublicUtil.isEmpty(applyStaffDto.getReason())) {
                throw new BusinessException(ErrorCodeEnum.GB10051006);
            }
        }

        DsmsStaff dsmsStaff = new DsmsStaff();
        dsmsStaff.setId(applyStaffDto.getStaffId());
        dsmsStaff.setApply(applyStaffDto.getApply());
        dsmsStaff.setReason(applyStaffDto.getReason());
        dsmsStaff.setUpdateInfo(login);

        return dsmsStaffMapper.updateByPrimaryKeySelective(dsmsStaff);
    }

    /**
     * 根据用户id获取服务人员信息
     *
     * @param userId the user id
     * @return the staff vo
     */
    @Override
    public StaffVo selectByUserId(Long userId) {

        return dsmsStaffMapper.selectByUserId(userId);
    }

    /**
     * 获取每年每个月的服务人员数量
     *
     * @param year the year-yyyy
     * @return the staff number vo list.
     */
    @Override
    public List<StaffNumberVo> queryStaffNumberList(String year) {

        return dsmsStaffMapper.queryStaffNumberList(year);
    }

    /**
     * 获取每年每个月的服务人员数量
     *
     * @param year the year-yyyy
     * @return the staff number vo list.
     */
    @Override
    public List<Map<String, Integer>> queryStaffNumberByMonth(String year) {
        Calendar cal = Calendar.getInstance();
        Integer month = cal.get(Calendar.MONTH) + 1;
        Integer y = cal.get(Calendar.YEAR);
        if (Integer.valueOf(year) < y) {
            month = 12;
        }
        List<String> months = new ArrayList<>();
        for (int i = month; i > 0; i = i - 1) {
            if (i < 10) {
                months.add(year + "-0" + (i + 1));
            } else {
                months.add(year + "-" + (i + 1));
            }
        }
        return dsmsStaffMapper.queryStaffNumberByMonth(months);
    }

    //查询当前服务人员所在片区
    @Override
    public DsmsStaff selectAreaByStaff(DsmsStaff dsmsStaff) {
        return dsmsStaffMapper.selectAreaByStaff(dsmsStaff);
    }

    //查询当前片区服务人员
    @Override
    public List<DsmsStaff> selectStaffByArea(DsmsStaff ds) {
        return dsmsStaffMapper.selectStaffByArea(ds);
    }

    /*
     * 查询该公司下是否有在职服务人员
     * */
    @Override
    public List<StaffVo> queryStaffVo(StaffQueryDto staffQueryDto) {
        return dsmsStaffMapper.queryStaffVo(staffQueryDto);
    }



}
